<template>
	
	<view class="content">
		
		<u-navbar back-text=" "
		leftIcon='account'
		:leftIconColor="tksetting.titlecolor" 
		:bgColor="tksetting.color" 
		:titleStyle="{color:tksetting.titlecolor}" 
		:title="title"  
		:autoBack="false"  
		:placeholder="true">
		</u-navbar>
		
		<view class="logo">
			<image   style="width: 150rpx; height: 150rpx; " :src="tksetting.img" alt="" /></image>
		</view>
		<view class="login">
			<u--form :model="form" ref="uForm">
				<u-form-item label="帐号:" prop="phone">
					<u-input v-model="form.phone" placeholder="请输入登陆账号" />
				</u-form-item>
				<u-form-item label="密码:" prop="password">
					<u-input type="password" v-model="form.password" placeholder="请输入密码"/>
				</u-form-item>
			</u--form>
			<u-button :loading="login.loading"  loadingText="登录中..."  :color="tksetting.color"  @click="submit">登录</u-button>
			
			<view class="reg"  :style="{color:tksetting.color}" @click="register">没有帐号？立即注册</view>
			
			
			<!-- #ifdef MP-WEIXIN -->
			 <u-line style="margin-top: 150rpx;"></u-line>
			 <u-gap height="40"></u-gap>
			 <view style="display: flex;flex-direction: column; align-items: center; gap: 12rpx;">
				 <u-button @click="quick_login" text="快捷登录"></u-button>
			 </view>
			 
			<!-- #endif -->
			
			<!-- #ifdef APP-PLUS -->
			<!-- <u-line style="margin-top: 150rpx;"></u-line>
			 <u-gap height="40"></u-gap>
			 <u-button class="custom-style" @click="wxlogin" icon="weixin-circle-fill" text="快捷登录">
			 </u-button>
			 -->
			<!-- #endif -->
			
	
		</view>
		
		
		
	</view>
</template>

<script>
import {toast,wxcode,clearStorageSync, setStorageSync, getStorageSync, useRouter,checklogin} from '@/utils/utils.js'
import { mapState } from 'vuex';
export default {
	data() {
		return {
			title:'用户登录',
			loginshow:false,
			login:{
				loading:false,
				status:false,
			},
			session_ke:'',
			xcxopenid:'',
			form: {
				phone: '',
				password: '',
				xcx_openid:''
			},
			xieyi:[],
			rules: {
				phone: [
					{ 
						required: true, 
						message: '请输入帐号', 
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change','blur'],
					}
				],
				password: [
					{
						required: true,
						message: '请输入密码', 
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change','blur'],
					}
				]
			}
		};
	},
	onReady() {
		// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
		this.$refs.uForm.setRules(this.rules)
	},
	async onLoad() {
		
		// #ifdef MP-WEIXIN
		   const data= await wxcode();
		   const wx_info=await this.$api.wxlogin({code:data.code})
		   const openids=JSON.parse(wx_info.data[1]);
		   console.log(openids)
		   if(openids.errcode){
			   toast('小程序获取信息失败')
		   }else{
			   this.session_ke=openids.session_key;
			   this.form.xcx_openid=openids.openid
		   }
		// #endif
	},
	onShow() {
		checklogin();
	},
	computed:{
		...mapState(['tksetting'])
	},
	methods: {
		submit() {
			const _this=this;
				_this.$refs.uForm.validate().then(res => {
						
						this.login={loading:true}
						_this.$api.login(this.form).then(res => {
							if (res.code == 0) {
								
								setStorageSync('token',res.data.token);
								_this.$u.vuex('userinfo', res.user);
								setStorageSync('user_id', res.user.id);
								toast("登录成功,正在转到首页")
								//APP模式下记录登录时间
								// #ifdef APP-PLUS
									const login_currentTimeStamp = Date.now(); // 获取当前时间戳
									setStorageSync('lastActiveTimestamp', login_currentTimeStamp);
								// #endif
								setTimeout(function(){
									useRouter('/pages/index/index',{} ,'reLaunch')
								},1000)
							} else {
								toast(res.msg)
								this.login={loading:false}
							}
						})		
								
				}).catch(errors => {
					//console.log('验证失败'); 
				})
		},
		async quick_login(){
			this.login={loading:true}
			uni.showLoading({
				title: '加载中',
				mask:true,
			});
			const _this=this;
			_this.$api.quicklogin({token:this.form.xcx_openid}).then(res=>{
				if (res.code == 0) {
					setStorageSync('token',res.data.token);
					_this.$u.vuex('userinfo', res.user);
					setStorageSync('user_id', res.user.id);
					toast("登录成功,正在转到首页")
					setTimeout(function(){
						useRouter('/pages/index/index',{} ,'reLaunch')
					},1000)
				} else {
					useRouter('/pages/public/register')
					this.login={loading:false}
				}
				
			})
			
			
		},
		register(){
			useRouter('/pages/public/register')
		},
		forgetPassWord(){
			useRouter('/pages/public/forget_password')
		},
		xieyi_check(n){
			//console.log(n.length)
			this.xieyi=n.length;
		},
		routs(id){
			useRouter('/pages/news/info',{id:id},'navigateTo')
		},
		async getPhoneNumber (e) {
			console.log(e.detail)
			let that=this;
			let param = {
				sessionKey:that.session_ke,
				data:e.detail.encryptedData,
				iv:e.detail.iv
			}
			
			let data = await that.$api.jiemi(param);
			
			if(data.code==0){
				this.loginshow=true;
				
			}else{
				toast("手机号获取错误,请关闭重试!")
			}
			
		},
		wxlogin(){
			uni.login({
				"provider": "weixin",
				"onlyAuthorize": true, // 微信登录仅请求授权认证
				success: function(event){
					const {code} = event
					console.log(event)
					this.$api.wxlogin({code:event.code,type:'app'}).then(res=>{
						console.log(res)
						//uni.setStorageSync('token',res.token)
					})
				},
				fail: function (err) {
					toast(err.code)
			        // 登录授权失败
			        // err.code是错误码
			    }
			})
		}
	}
};
</script>
<style lang="scss" scoped>	
    
	.content {
		width:100%;
	}
	.logo{
		 display: flex;
		 justify-content: space-around;
		 align-items: center;
		 height: 300rpx;
	}
	.login{
		width: 70%;
		margin: 0 auto;
		margin-top: 50rpx;
		
		.bgcolor{
			// margin-top: 30rpx;
			// background-color: $uni-color-tikucolor;
		}
		
	}
	.title {
		text-align: center;	
		margin: 80rpx 0 0 0;
	}
	.reg{float: right;padding:30rpx 0 30rpx 0;color:#2979ff;}
	.forgetPassword{float: left;padding:30rpx 0 30rpx 0;color:#2979ff;}
</style>